package com.example.fz338.ui.home;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.fz338.R;
import com.example.fz338.adapter.HomeAdapter;
import com.example.fz338.adapter.ImageAdapter;
import com.example.fz338.adapter.ImageTitleNumAdapter;
import com.example.fz338.bean.NewsBean;
import com.example.fz338.databinding.FragmentHomeBinding;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private HomeViewModel homeViewModel;
    //
    private HomeAdapter homeAdapter;
    private Banner<?, BannerAdapter<?,?>> banner;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        RecyclerView recyclerView = root.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        homeAdapter = new HomeAdapter(null);
        recyclerView.setAdapter(homeAdapter);
        homeAdapter.setEmptyView(R.layout.empty_home); // 设置没有数据加载出来时候的默认页面
        View headerView = inflater.inflate(R.layout.header_home, container, false);
        homeAdapter.setHeaderView(headerView);
        homeAdapter.setHeaderWithEmptyEnable(true);
        // 轮播图 banner的一些设置
        banner = headerView.findViewById(R.id.banner);

        banner.addBannerLifecycleObserver(this) // 添加生命周期观察者 (观察者模式=订阅=onChange
                .setPageTransformer(new ZoomOutPageTransformer())// 设置viewpager的切换效果
                .setBannerGalleryMZ(20, 0.8f) // 样式 	魅族效果
                .start();
        List<Integer> list = new ArrayList<>();
        for(int i=0; i<3; i++) {
            list.add(R.drawable.pic_item_list_default);
            // 手动存入 图片加载失败 情况下 的 默认轮播图×3
        }
        banner.setAdapter(new ImageAdapter(list));

        // 刷新布局
        RefreshLayout refreshLayout = root.findViewById(R.id.refreshLayout);
        // 刷新监听
        refreshLayout.setOnRefreshListener( layout -> {
            layout.finishRefresh(2000/*,false*/); //传入false表示刷新失败
            getAdList();
            getNewsList();
        });
        refreshLayout.setOnLoadMoreListener(layout -> {
            layout.finishLoadMore(2000/*,false*/); //传入false表示加载失败
            Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
        });

        getAdList();// 测试用注释 查看默认轮播图时
        getNewsList();// 测试用注释 查看默认轮播图时

        // 主页 python 图表的点击事件
        LinearLayout linearLayout_python = headerView.findViewById(R.id.linearLayout_python);
        linearLayout_python.setOnClickListener(v -> Navigation.findNavController(v)
                .navigate(R.id.action_navigation_home_to_pythonFragment));
        homeAdapter.setOnItemClickListener(((adapter, view, position) -> {
            Bundle bundle = new Bundle();
            bundle.putString("url", homeAdapter.getData().get(position).getNewsUrl());
            Navigation.findNavController(view).navigate(R.id.action_navigation_home_to_webFragment, bundle);
        }));

        return root;
    }

    private void getAdList() {
        homeViewModel.getAdList().observe(getViewLifecycleOwner(), newsBeans -> {
            // 闪退是因为 newsBeans(List<NewsBean>) == null 本质原因是没给 安卓模拟器 连 WIFI 所以没获取到数据
            if(newsBeans==null) {
                Log.i("newsBeans==", "null");
                Log.e("获取不到数据","可能是tomcat没打开 或者 安卓虚拟机没连WIFI");
                return;
            }

            banner.setAdapter(new ImageTitleNumAdapter(newsBeans));
            banner.setOnBannerListener(((data, position) -> {
                Bundle bundle = new Bundle();
                bundle.putString("url", ((NewsBean) data).getNewsUrl());
                Navigation.findNavController(banner)
                        .navigate(R.id.action_navigation_home_to_webFragment, bundle);
            }));
            // 控制台 Logcat 乱码的解决方法 https://blog.csdn.net/zgrcoder/article/details/136152344
//            for(NewsBean newsBean : newsBeans) {
//                Log.i("AD:", newsBean.getNewsName());
//            }
        });
    }

    private void getNewsList() {
        homeViewModel.getNewsList().observe(getViewLifecycleOwner(), newsBeans -> {
            if(newsBeans==null) {
                Log.i("newsBeans==", "null");
                Log.e("获取不到数据","可能是tomcat没打开 或者 安卓虚拟机没连WIFI");
                return;
            }
            homeAdapter.setList(newsBeans);
//            for(NewsBean newsBean : newsBeans) {
//                Log.i("News:", newsBean.getNewsName());
//            }
        });
    }

    // 这个好像没用 ?
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}